<template>
  <div class="chat-card" :style="chooseStyle" @click="selectRoom">
    <div class="chat-card__left">
       <el-avatar :size="40" :src="chatInfo.info.avatar">
        <img v-if="isGroup" src="../../assets/picture/gruopAvatar.png"/>
        <img v-else src="../../assets/picture/defaultAvatar.png"/>
      </el-avatar>
      <div class="chat-card__left__info">
        <div class="chat-card__left__info__name">
        {{ chatInfo.info.nickName || chatInfo.info.name }}</div>
        <div class="chat-card__left__info__message">
          <span v-html="redLetterPrompt"></span>
        </div>
      </div>
    </div>
    <div class="chat-card__right">
      <div class="chat-card__right__time">{{ lastTime }}</div>
      <div class="chat-card__right__unread" v-if="unread !== 0">{{ unread }}</div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import _ from 'lodash'
import moment from 'moment'
import { getStorage } from '../../js/utils'
import { setNotificationMsg } from '../../utils/messageFormatFunction.js'
export default {
  components: { },
  props: ['thisRoomId', 'chatInfo'], // thisRoomId 为当前卡片的聊天室的ID
  computed: {
    ...mapState('app', ['chatList', 'groupList', 'selectMember', 'roomId', 'unreadList', 'friendList', 'chatRoomInfo', 'chatListBase']),
    // 当前聊天室未读数
    unread: function () {
      if (this.unreadList[this.thisRoomId]) {
        if (this.unreadList[this.thisRoomId] > 99) {
          return '99+'
        } else {
          return this.unreadList[this.thisRoomId]
        }
      } else {
        return 0
      }
    },
    // 选中房间是否是当前房间
    choose: function () {
      return this.roomId === this.thisRoomId
    },
    // 选中房间的样式
    chooseStyle: function () {
      if (this.choose) {
        return { background: 'rgba(247,247,247,1)' }
      } else {
        return {}
      }
    },
    // 当前聊天室列表最后一条信息时间
    lastTime: function () {
      const messageList = this.chatList[this.thisRoomId]
      if (messageList && messageList.length > 0 && messageList[messageList.length - 1].timestamp !== 'Invalid date') {
        return moment(messageList[messageList.length - 1].timestamp * 1).format('HH:mm')
      } else {
        return ''
      }
    },
    isGroup: function () {
      const index = _.findIndex(this.groupList, e => e.roomId + '' === this.thisRoomId)
      if (index === -1) {
        return false
      } else {
        return true
      }
    },
    lastmsg: function () {
      let result = ''
      const messageList = this.chatList[this.thisRoomId]
      const [last] = this.chatList[this.thisRoomId].slice(-1)
      if (!last) return
      const { subType, roomId: currentRoomId, msg, isMe, senderId } = last
      let sendName = ''
      if (this.isGroup && !isMe) {
        const groupMembers = this.chatRoomInfo[currentRoomId].data
        const who = groupMembers.find(i => i.userId + '' === senderId)
        if (who) {
          sendName = `${who.name}:`
        }
      }

      switch (subType) {
        case 'image':
          result = `${sendName}[图片]`; break
        case 'video':
          result = `${sendName}[视频]`; break
        case 'file':
          result = `${sendName}[文件]`; break
        case 'audio':
          result = `${sendName}[音频]`; break
        case 'text':
          result = `${sendName}${msg}`; break
        case 'at':
          result = `${msg}`; break
        default:
          const parame = {
            info: last,
            isGroup: this.isGroup,
            chatRoomInfo: this.chatRoomInfo,
            friendList: this.friendList,
            roomId: currentRoomId
          }
          result = setNotificationMsg(parame)
      }
      result = this.someoneAtMe(messageList) + result
      return result
    },
    redLetterPrompt: function () {
      // 红字消息提示，
      // 优先级： 有人@我 + 消息 > 草稿：草稿消息 > 消息
      let msg = this.lastmsg || ''
      const currentBase = this.chatListBase[this.thisRoomId]
      if (currentBase) {
        const { content, someoneAtMe } = currentBase
        if (content && content.trim() !== '') {
          msg = `<span style="color: #ff4242">[草稿]</span>${content}`
        }
        if (someoneAtMe) {
          msg = `<span style="color: #ff4242">[有人@我]</span>${this.lastmsg}`
        }
      }
      return msg
    }
  },

  async created () {
    this.getUser()
  },
  data () {
    return {
      user: {},
      notificationDefaultAvatar: require('../../assets/picture/logo.png')
    }
  },
  watch: {
    chatList: {
      handler (newdata) {
        this.getUser()
      }
    },
    // choose: {
    //   handler (newdata) {
    //     const _unreadList = _.cloneDeep(this.unreadList)
    //     _unreadList[this.thisRoomId] = 0
    //     this.$store.dispatch('app/setUnreadList', _unreadList)
    //   }
    // },
    friendList: {
      async handler (newdata) {
        const index = _.findIndex(this.friendList, e => {
          return e.roomId + '' === this.thisRoomId + ''
        })
        const _index = _.findIndex(this.groupList, e => {
          return e.roomId + '' === this.thisRoomId + ''
        })
        if (index !== -1) {
          this.user = this.friendList[index]
        } else if (_index !== -1) {
          this.user = this.groupList[_index]
        }
      }
    },
    lastmsg () {
      if (document.visibilityState === 'hidden' && window.Notification && window.Notification.permission === 'granted' && !this.isMe()) {
        this.sendNotification()
      }
    }
  },
  methods: {
    isMe () {
      const messageList = this.chatList[this.thisRoomId]
      return messageList.length && messageList[messageList.length - 1].isMe
    },
    sendNotification () {
      // eslint-disable-next-line no-new
      if (this.notification) {
        this.notification.close()
      }
      this.notification = new Notification(this.chatInfo.info.nickName || this.chatInfo.info.name || '小蓝豆', {
        body: this.lastmsg,
        icon: this.chatInfo.info.avatar || this.notificationDefaultAvatar
      })
      this.notification.onclick = () => {
        window.focus()
        this.notification.close()
      }
    },
    getNameByObjArr (arr) {
      return arr.reduce((accumu, current) => `${accumu}${current.name},`, '')
    },
    getNameByArr (arr) {
      const res = this.chatRoomInfo[this.roomId].data.filter(i => arr.includes(i.userId + ''))
      return res.reduce((accumu, current) => `${accumu}${current.name},`, '')
    },
    someoneAtMe (messageList) {
      const index = _.findLastIndex(messageList, e => e.islooking === false)
      const isMeNameId = getStorage('aillo_id') ? getStorage('aillo_id') : getStorage('aillo_name')
      let msg = ''
      if (index !== -1 && messageList[index].atModelList) {
        messageList[index].atModelList.forEach(t => {
          if (t.userId + '' === isMeNameId + '' || t.userId + '' === '-1' || t.userName === isMeNameId) {
            msg = `<span style="color: #ff4242">[有人@我]</span>`
          }
        })
      }
      return msg
    },
    getMsg (msg, type) {
      switch (type) {
        case 'video':
          return '[视频]'
        case 'file':
          return '[文件]'
        case 'image':
          return '[图片]'
        default:
          return msg
      }
    },
    async getUser () {
      const index = _.findIndex(this.friendList, e => {
        return e.roomId + '' === this.thisRoomId + ''
      })
      const _index = _.findIndex(this.groupList, e => {
        return e.roomId + '' === this.thisRoomId + ''
      })
      if (index !== -1) {
        this.user = this.friendList[index]
      } else if (_index !== -1) {
        this.user = this.groupList[_index]
      }
    },
    selectRoom () {
      this.$store.dispatch('app/setChatPanelType', 'chat')
      this.$store.dispatch('app/setRoomId', this.thisRoomId)
      if (this.thisRoomId !== '100008') {
        this.$store.dispatch('app/setSelectMember', this.user)
      } else {
        this.$store.dispatch('app/setSelectMember', this.chatInfo.info)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.chat-card {
  user-select: none;
  height: 59px;
  padding: 0 7px;
  display: flex;
  justify-content: space-between;
  align-content: center;
  cursor: pointer;
  &__left {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    &__avatar {
      width: 40px;
      height: 40px;
      border-radius: 500px;
    }
    &__info {
      margin-left: 10px;
      &__name {
        font-size: 16px;
        font-family: Source Han Sans CN;
        font-weight: 400;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        width: 170px;
      }
      &__message {
        font-size: 12px;
        font-family: Source Han Sans CN;
        font-weight: 400;
        overflow: hidden;
        text-overflow: ellipsis;
        -o-text-overflow: ellipsis;
        white-space: nowrap;
        width: 138px;
        height: 18px;
        color: rgba(153, 153, 153, 1);
        display: block;
      }
    }
  }
  &__right {
    display: flex;
    flex-direction: column;
    justify-content: center;
    &__time {
      font-size: 10px;
      font-family: Source Han Sans CN;
      font-weight: 400;
      color: rgba(153, 153, 153, 1);
      margin-bottom: 2px;
    }
    &__unread {
      background: rgba(233, 51, 35, 1);
      border-radius: 100px;
      display: flex;
      justify-content: center;
      align-items: center;
      color: white;
      font-size: 9px;
      max-width: 30px;
      min-width: 16px;
    }
  }
}
</style>
